<template>
 <div id="dep">
     <div>
         <el-row>
           <el-autocomplete class="inline-input" v-model="input" :fetch-suggestions="querySearch"
                    placeholder="部门名称"
                    :trigger-on-focus="false" clearable @clear="getAlldepartment">
            </el-autocomplete>
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
            <el-button type="primary" @click="dialogFormVisible1 = true;" icon="el-icon-plus" class="fr">新增部门</el-button>
         </el-row>
     </div>
    <el-table :data="tableData" height="325" border style="width: 100%" v-loading="loading">
        <el-table-column prop="did" label="编号"></el-table-column>
        <el-table-column prop="dname" label="部门名称"></el-table-column>
        <el-table-column prop="dtime" label="创建时间">
          <template slot-scope="scope">
            {{scope.row.dtime | dateFormat}}
          </template>
        </el-table-column>
        <el-table-column prop="dfounder" label="创建人"></el-table-column>
        <el-table-column prop="diid" label="员工编号" v-if="show"></el-table-column>
        <el-table-column prop="dmanager" label="部门经理"></el-table-column>
        <el-table-column prop="dsynopsis" label="简介" width="400px"></el-table-column>
        <el-table-column  label="操作" width="330px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="dialogFormVisible = true;edit(scope.row)" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="success" icon="el-icon-edit" @click="dialogFormVisible2 = true;jingli(scope.row)">设置经理</el-button>
            <el-button size="mini" type="danger" @click="open(scope.row);" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
    </el-table>
    <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 15, 20]"
            :page-size="number"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
    </div>


    <el-dialog title="编辑" :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="form">
        <el-form-item label="部门名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" name="pname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" :label-width="formLabelWidth">
          <el-input type="textarea" name="dsynopsis" v-model="form.desc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false;off();">取 消</el-button>
        <el-button type="primary" @click="submitForm('form');dialogFormVisible = false;">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="新增部门" :visible.sync="dialogFormVisible1">
      <el-form :model="form1" ref="form1">
        <el-form-item label="部门名称" :label-width="formLabelWidth">
          <el-input v-model="form1.name" autocomplete="off" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="简介" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="form1.desc" placeholder="请输入部门的介绍"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false;off();">取 消</el-button>
        <el-button type="primary" @click="submitForm1('form1');dialogFormVisible1 = false">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="设置经理" :visible.sync="dialogFormVisible2">
      <el-form :model="form2" ref="form2">
        <el-form-item label="选择范围" :label-width="formLabelWidth">
          <el-switch v-model="value1" active-text="本部门选择" inactive-text="全员选择" @change="getAllinformation()"></el-switch>
        </el-form-item>
        <el-form-item label="经理" :label-width="formLabelWidth">
          <el-select v-model="form2.region" placeholder="请选择本部门经理">
            <el-option v-for="item in jingliname" :key="item.iid" :label="item.iname" :value="item.iname" @click.native="test(item.iid)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false;off();">取 消</el-button>
        <el-button type="primary" @click="submitForm2('form2');dialogFormVisible2 = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

  <script>
  import qs from 'qs';
    export default {
      data() {
        return {
          currentPage: 1,
          tableData:[],
          newtableData:[],
          show:false,
          total:null,
          input: '',
          value1: true,
          number:5,
          loading: false,
          dialogFormVisible: false,
          dialogFormVisible1:false,
          dialogFormVisible2:false,
          jingliname:[],
          getHospitalData: [],// 根据输入值  查询到的结果 
          remindData: [], // 存放提醒框的数据
          form: {
            name: '',
            desc: '',
            did:''
          },
          form1: {
            name: '',
            desc: '',
            did:''
          },
          form2:{
            region:'',
            did:'',
            dname:'',
            iid:'',
            diid:''
          },
          formLabelWidth: '120px'
          }
      },
      created(){
        this.getAlldepartment();
      },
      methods: {
        handleSizeChange(val) {
          this.number = val       
          this.getTableData()    
          console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
          this.currentPage = val
          this.getTableData()
          console.log(`当前页: ${val}`);
        },
        open(e) {
          this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.delete(e);
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });
        },
        getAlldepartment(){
          this.loading=true;
          this.$http.get("https://7d5184241f35.ngrok.io/api/getAlldepartment").then((response)=>{
            if(response.data.length!=0){
              this.total=response.data.length;
              this.newtableData=response.data;
              this.tableData = this.newtableData.slice((this.currentPage - 1)*this.number,this.currentPage*this.number);
              this.loading=false;
            }else{
              this.$message.error('获取数据失败！');
            }
          })
        },
        getTableData(){
          this.tableData = this.newtableData.slice((this.currentPage - 1)*this.number,this.currentPage*this.number);
        },
        //搜索
        querySearch(queryString, cb) { 
          console.log(queryString);
          if (this.input !== "") { 
            this.remindData = []; 
            this.$http.get('https://7d5184241f35.ngrok.io/api/seach/'+queryString).then((response)=> { 
              this.getHospitalData =response.data; 
              this.getHospitalData.forEach((item) => { 
                let obj = { value: ""}; 
                obj.value = item.dname; 
                this.remindData.push(obj); 
              }); 
              let nameTipsArray = this.remindData; 
              cb(nameTipsArray); 
            }); 
          } 
        },
        search(){
          console.log(this.input);
          if(this.input!=""){
            this.getHospitalData.forEach((item) => { 
                if(item.dname==this.input){
                  this.tableData=[];
                  this.tableData.push(item);
                  this.total=this.tableData.length;
                }
            }); 
          }else if(this.input==""){
            this.tableData=this.newtableData;
            this.total=this.tableData.length;
            this.getTableData();
          }
        },
        off(){
          this.$message('已取消');
        },
        //编辑部门
        edit(e){
            this.form.name=e.dname;
            this.form.desc=e.dsynopsis;
            this.form.did=e.did;
        },
        resetForm(formName) {
          this.$refs[formName].resetFields();
        },
        submitForm(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.update();
            } else {
              this.$message.error('修改失败');
              return false;
            }
          });
        },
        submitForm1(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.add();
            } else {
              this.$message.error('添加失败');
              return false;
            }
          });
        },
        submitForm2(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.setjingli();
            } else {
              this.$message.error('设置经理失败');
              return false;
            }
          });
        },
        //修改部门信息
        update(){
          let info={
            dname:this.form.name,
            dsynopsis:this.form.desc,
            did:this.form.did
          }
          this.$http.put('https://7d5184241f35.ngrok.io/api/updatedepartment',qs.stringify(info)).then((response)=> { 
            console.log(response.data);
            if(response.data.flag===1){
              this.$message({type: 'success',message: '修改成功!'});
              this.getAlldepartment();
            }else{
              this.$message.error('修改失败！');
            }
          });
        },
        //添加部门信息
        add(){
          let currentTime = new Date().getFullYear() +"-" +(new Date().getMonth() + 1) +"-" +new Date().getDate();
          let info={
            dname:this.form1.name,
            dtime:currentTime,
            dfounder:'admin',
            dmanager:null,
            dsynopsis:this.form1.desc,
          }
          this.$http.post('https://7d5184241f35.ngrok.io/api/adddepartment',qs.stringify(info)).then((response)=> { 
            console.log(response.data);
            if(response.data.flag===1){
              this.$message({type: 'success',message: '添加成功!'});
              this.form1.name='';
              this.form1.desc='';
              this.getAlldepartment();
            }else{
              this.$message.error('添加失败！');
            }
          });
        },
        //删除部门信息
        delete(e){
          let id=e.did;
          console.log(id);
          this.$http.delete('https://7d5184241f35.ngrok.io/api/deletedepartment/'+id).then((response)=> { 
            if(response.data.flag===1){
              this.$message({type: 'success',message: '删除成功!'});
              this.getAlldepartment();
            }else{
              this.$message.error('删除失败！');
            }
          });
        },
        //设置经理
        jingli(e){
          this.form2.did=e.did;
          this.form2.dname=e.dname;
          this.form2.diid=e.diid;
          this.getAllinformation();
        },
        test(data) {
          this.form2.iid=data;
        },
        setjingli(){
          let currentTime = new Date().getFullYear() +"-" +(new Date().getMonth() + 1) +"-" +new Date().getDate();
          let info={
            did:this.form2.did,//选中的部门id
            dtime:currentTime,
            dfounder:'admin',
            dname:this.form2.dname,//选中的部门名称
            diid:this.form2.diid,//原先经理的id
            dmanager:this.form2.region,//想选择的经理名字
            pname:this.form2.dname+'经理',
            iid:this.form2.iid//想选择的经理id
          }
          console.log(info);
          this.$http.put('https://7d5184241f35.ngrok.io/api/setdmanager',qs.stringify(info)).then((response)=> { 
            console.log(response.data);
            if(response.data.flag===1 && response.data.cp===0){
              this.$message({type: 'success',message: '设置经理成功!'});
            }else if(response.data.flag===2 && response.data.cp===0){
              this.$message.error('设置经理失败！');
            }else if(response.data.cp===1 && response.data.flag===1){
              this.$notify({title: '成功',message: '自动创建该部门经理职位成功!',type: 'success',offset: 100});
              this.$message({type: 'success',message: '设置经理成功!'});
            }else if(response.data.cp===1 && response.data.flag===2){
              this.$notify({title: '成功',message: '自动创建该部门经理职位成功!',type: 'success',offset: 100});
              this.$message.error('设置经理失败！');
            }else if(response.data.cp===2){
              this.$notify({title: '失败',message: '自动创建该部门经理职位失败!',type: 'warning',offset: 100});
            }
            this.getAlldepartment();
          });
        },
        getAllinformation(){
          this.$http.get("https://7d5184241f35.ngrok.io/api/getAllinformation").then((response)=>{
            if(response.data.length!=0){
              let information=[];
              this.jingliname=[];
              let dname=this.form2.dname;
              information=response.data;
              if(this.value1==true){
                for(var i=0;i<information.length;i++){
                  if(information[i].idname==dname){
                      this.jingliname.push(information[i]);
                  }
                }
              }else{
                this.jingliname=information;
              }
            }else{
              this.$message.error('获取数据失败！');
            }
          })
        },
      }
    }
  </script>
  <style scoped>
  #dep{
    padding: 20px;
  }
  .el-autocomplete{
      width: 60%;
      margin: 20px 0px 20px 5px;
  }
  .el-select{
    width: 80%;
  }
  .fr{
      float: right;
      margin: 20px 20px 20px 0px;
  }
  .el-pagination{
      text-align: center;
  }
  .el-table{
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  }
  </style>